<?php

namespace app\common\service;

use app\common\facade\supplier\Supplier;
use app\model\CouponOrderSid;
use think\facade\Db;
use think\facade\Log;

class Meituan
{
    private $appkey;
    private $secret;
    private $error;

    public function __construct($agentId)
    {

        //该代理是否为接口，还是系统的接口
//        $api = \app\model\Meituan::query()
//            ->where('agent_id', $agentId)
//            ->find();
//        if (empty($api)) {
//            throw new \think\Exception('美团联盟账号未配置');
//        }

        $supplier = Supplier::init(PRODUCT_MEITUAN_TAKEOUT_SERV);


        try {

            $this->appkey = $supplier->getAppkey();
            $this->secret = $supplier->getSecret();
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    public function request_post($url = '', $param = [], $ispost = false)
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        if ($ispost) {
            $vars = http_build_query($param, '', '&');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
        } else {
            $p = '';
            foreach ($param as $key => $value) {
                $p = $p . $key . '=' . $value . '&';
            }
            if (preg_match('/\?[\d\D]+/', $url)) {//matched ?c
                $p = '&' . $p;
            } elseif (preg_match('/\?$/', $url)) {//matched ?$
                $p = $p;
            } else {
                $p = '?' . $p;
            }
            $p = preg_replace('/&$/', '', $p);
            $url = $url . $p;
        }
        $postUrl = $url;
        //初始化curl //转义
        //抓取指定网页
        curl_setopt($ch, CURLOPT_URL, $postUrl);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //规避SSL验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //跳过HOST验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public function rtnotify($params)
    {
        $url = 'https://openapi.meituan.com/api/rtnotify';
        $data = [
            'key' => $this->appkey,
            'oid' => $params['oid'],
            'full' => 1,
            'type' => $params['type'],
        ];
        $data['sign'] = $this->genSign($data);
        return $this->request_post($url, $data);
    }

    //订单列表查询(新)
    //https://openapi.meituan.com/api/orderList
    public function orderlist($params)
    {
        $url = "https://openapi.meituan.com/api/orderList";
        $data = [
            'key' => $this->appkey,
            'ts' => time(),
            'type' => $params['type'], //0团购订单 2酒店订单 4外卖订单 5话费&团好货订单 6闪购订单【商超】 8优选订单
            'startTime' => $params['startTime'], //时间戳
            'endTime' => $params['endTime'],
            'page' => $params['page'] ?? 1,
            'limit' => $params['limit'] ?? 100,
            'queryTimeType' => "1"
        ];
        $data['sign'] = $this->genSign($data);

        return $this->request_post($url, $data);
    }

    /**
     * 单订单查询接口（新版）
     *
     * https://union.meituan.com/v2/apiDetail?id=24
     *
     * 请求地址：https://openapi.meituan.com/api/order
     */
    public function getOrder($params)
    {
        $url = 'https://openapi.meituan.com/api/order?';
        $data = [
            'appkey' => $this->appkey,
            'actId' => $params['actId'], // 活动id
            'full' => 1,
            'orderId' => $params['orderId'],
        ];
        $data['sign'] = $this->genSign($data);

        $url .= http_build_query($data);

        $res = curlGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    //签名(sign)生成逻辑
    public function genSign($params)
    {
        unset($params["sign"]);
        ksort($params);
        $str = $this->secret; // $secret为分配的密钥
        foreach ($params as $key => $value) {
            $str .= $key . $value;
        }
        $str .= $this->secret;
        $sign = md5($str);
        return $sign;
    }

    public function curlGet($url, $header = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if (empty($header)) {
            $header = [
                'Content-Type: application/json;charset=utf-8',
            ];
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

    /**
     * 活动名称：美团外卖CPS+CPA推广活动
     * 活动 id：2
     *
     * 活动名称：闪购CPS推广
     * 活动 id：4
     *
     * params
     * user_id 用户id
     * act_id 活动类型：美团联盟后台获取
     */
    public function generateLink($params)
    {

        // 是否已经生成
//        $link = Db::name('meituan_activity_link')
//            ->where('user_id', $params['user_id'])
//            ->where('agent_id', $params['agent_id'])
//            ->where('channel_id', $params['channel_id'])
//            ->where('act_id', $params['act_id'])
//            ->value('url');
//        if ($link) {
//            return $link;
//        }

        $sid = CouponOrderSid::generate($params['agent_id'], $params['channel_id'], $params['user_id'], $params['act_id']);

        $url = 'https://openapi.meituan.com/api/generateLink?';
        $postData = [
            'actId' => $params['act_id'],
            'appkey' => $this->appkey,
            'sid' => $sid,
            'linkType' => $params['act_id'] == 22 ? 3 : 1, // 链接类型，枚举值： 1 h5链接 2 deeplink(唤起)链接 3 中间页唤起链接 4 微信小程序唤起路径
            'shortLink' => 0, // 获取长链还是短链 0长链 1短链
        ];

        if (!empty($params['from']) && $params['from'] == 'wechat') {
            $postData['linkType'] = 4;
        }
        if (!empty($params['from']) && $params['from'] == 'app') {
            $postData['linkType'] = 3;
        }
        if (!empty($params['from']) && $params['from'] == 'client') {
            $postData['linkType'] = 4;
        }

        $postData['sign'] = $this->genSign($postData);
        $url .= http_build_query($postData);
        $res = $this->curlGet($url);
        Log::info($res);
        $res = json_decode($res, true);
        if (!isset($res['status']) || $res['status'] != 0) {
            $this->error = json_encode($res);
            return false;
        }

//        Db::name('meituan_activity_link')->insert([
//            'user_id' => $params['user_id'],
//            'agent_id' => $params['agent_id'],
//            'channel_id' => $params['channel_id'],
//            'sid' => $sid, // 推广位规则：用户id + 's' + 代理商id + 's' + 渠道id
//            'act_id' => $params['act_id'],
//            'url' => $res['data'],
//        ]);
        return $res['data'];
    }

    /**
     * 商品列表搜索
     *
     * @param   $user_id        用户id
     * @param   $lng            经度
     * @param   $lat            纬度
     * @param   $page           当前页
     * @param   $size           每页结果数
     */
    public function skuQuery($params)
    {
        $sid = CouponOrderSid::generate($params['agent_id'] ?? 0, $params['channel_id'] ?? 0, $params['user_id'] ?? 0);

        $query = [
            'businessType' => 6,
            'ts' => time(),
            'appkey' => $this->appkey,
            'sid' => $sid,
            'pageSize' => $params['size'] ?? 10,
            'pageNO' => $params['page'] ?? 1,
            'longitude' => $params['lng'],
            'latitude' => $params['lat'],
        ];
        $query['sign'] = $this->genSign($query);
        $url = 'https://openapi.meituan.com/sku/query?' . http_build_query($query);
        $res = $this->curlGet($url);
        $res = json_decode($res, true);
        if (!isset($res['code']) || $res['code'] != 0) {
            return false;
        }
        return $res['data'];
    }

    public function getError()
    {
        return $this->error;
    }
}
